package cn.liuyang.tinyioc.beans.factory;

import cn.liuyang.tinyioc.BeanReference;
import cn.liuyang.tinyioc.beans.BeanDefinition;
import cn.liuyang.tinyioc.beans.PropertyValue;

import java.lang.reflect.Field;

public class AutowiredCapableBeanFactory extends AbstractBeanFactory {


    @Override
    protected Object doCreateBean(BeanDefinition definition) throws Exception {
        Object bean = createBeanInstance(definition);
        definition.setBean(bean);
        applyPropertyValues(bean, definition);
        return bean;
    }

    private void applyPropertyValues(Object bean, BeanDefinition definition) throws Exception {
        for (PropertyValue propertyValue : definition.getPropertyValues().getPropertyValues()) {
            Field field = bean.getClass().getDeclaredField(propertyValue.getName());
            field.setAccessible(true);
            Object value = propertyValue.getValue();
            if (value instanceof BeanReference) {
                BeanReference beanReference = (BeanReference) value;
                value = getBean(beanReference.getBeanName());
            }
            field.set(bean, value);
        }
    }

    private Object createBeanInstance(BeanDefinition definition) throws Exception {
        return definition.getBeanClass().newInstance();
    }
}
